const cloud = require('wx-server-sdk')

cloud.init({
	env: cloud.DYNAMIC_CURRENT_ENV,
})

exports.main = async (event) => {
	try {
		const { OPENID } = cloud.getWXContext()
		const { spaceid, title, content } = event

		
		const DB = cloud.database()

		const timeStamp = new Date().getTime()

		const article = {
			collector: [],
			belong_space: spaceid,
			last_modified_time: timeStamp,
			title,
			content,
			author: OPENID,
			create_time: timeStamp,
		}

		const newArticleRes = await DB.collection('gn_article').add({
			data: article,
		})

		const getHistoricalSpace = await DB.collection('gn_space').doc(spaceid).get()
		const newArticle = getHistoricalSpace.data.article
		newArticle.push({
			_id: newArticleRes._id,
			title,
		})
		await DB.collection('gn_space')
			.doc(spaceid)
			.update({
				data: {
					article: newArticle,
				},
			})

		const newSpaceInfo = await DB.collection('gn_space').doc(spaceid).get()

		return {
			code: 0,
			msg: '创建成功',
			data: {
				space: newSpaceInfo.data,
			},
		}
	} catch (err) {
		throw err
	}
}
